import pymongo

"""
docker pull mongo:latest
docker run -itd --name md -p 5408:27017 mongo
docker exec -it md mongo admin
db.createUser({ user:'admin',pwd:'12345678',roles:[ { role:'userAdminAnyDatabase', db: 'admin'},"readWriteAnyDatabase"]});
db.auth('admin', '12345678')
返回1 则success
"""


def connect_mongo_db():
    # client = pymongo.MongoClient('mongodb://47.99.215.64:27017/'
    #                              , username='admin'
    #                              , password='12345678'
    #                              , authMechanism='SCRAM-SHA-1',
    #                              connect=False
    #                              )
    #
    # client = pymongo.MongoClient(host='47.99.215.64',
    #                              port=5408,
    #                              username='admin',
    #                              password='12345678',
    #                              authSource='md')
    client = pymongo.MongoClient('mongodb://admin:12345678@47.99.215.64:5408/')
    return client['md']


def handler():
    db = connect_mongo_db()
    coll = db['first']
    # coll.insert_one(
    #     {"username": "summit", "age": 18}
    # )

    one = coll.find({"age": 18})
    for o in list(one):
        print(o)


def insert():
    db = connect_mongo_db()
    coll = db['first']
    coll.insert_one(
        {"like": "躺"}
    )


def find_all():
    db = connect_mongo_db()
    coll = db['first']
    one = coll.find()
    for o in list(one):
        print(o)


def update():
    db = connect_mongo_db()
    coll = db['first']
    coll.update_one({"username": "summit"}, {"$set": {"username": "jack"}})


def delete():
    db = connect_mongo_db()
    coll = db['first']
    coll.delete_many({"like": '躺'})


if __name__ == '__main__':
    # handler()
    # update()bjectId('61496c2080f32d538de2a0f2'), 'username': 'jack', 'age': 18}
    # {'_id': ObjectId('61496cbdc4c99f43d6954527'), 'username': 'summit', 'age': 18}
    # {'_id': ObjectId('61496cd5371750aad01c7bcb'), 'username': 'summit', 'age': 18}
    # {'_id': ObjectId('61496df3543632bd9a67e582'), 'like': '躺'}
    # insert()
    delete()
    find_all()
